package com.kye.express.business.jd.address;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.TextUtils;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewAfterTextChangeEvent;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.jd.address_select.AddressSelectActivity;
import com.kye.express.business.jd.address_select.AddressSelectLevel;
import com.kye.express.databinding.ActivityJdAddressAddEditBinding;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.address.AddressBean;
import com.kye.model.bean.jd.address.JDAddressBean;
import com.kye.model.bean.jd.address.request.RequestAddModifyAddress;
import com.kye.model.bean.user.User;

import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.subjects.PublishSubject;

public class JDAddressAddEditActivity extends BaseAppCompatActivity implements JDAddressAddEditConstract.JDAddressAddEditView {

    private final static String TAG_ADDRESS_INIT = "TAG_ADDRESS_INIT";
    private final static String TAG_ADDRESS_NEW = "TAG_ADDRESS_NEW";
    private JDAddressBean initAddress;
    private JDAddressBean newAddress;
    private JDAddressAddEditConstract.JDAddressAddEditPresenter presenter;
    private ActivityJdAddressAddEditBinding binding;
    private Dialog dialog;

    private Observable<String> receiveNameObservable;
    private Observable<String> receiveAddressDetailObservable;
    private Observable<String> receiveAddressObservable;
    private Observable<String> receivePhoneObservable;
    private PublishSubject<String> receiveAddress = PublishSubject.create();
    private PublishSubject<String> receivePhone = PublishSubject.create();

    /**
     * 当前地址4级
     */
    private AddressBean selectedProvince;
    private AddressBean selectedCity;
    private AddressBean selectedCountry;
    private AddressBean selectedTown;

    private RequestAddModifyAddress requestAddModifyAddress;
    private User userInfo;

    public static void startActivity(Activity activity, int requestCode, JDAddressBean jdAddressBean) {
        Intent intent = new Intent(activity, JDAddressAddEditActivity.class);
        intent.putExtra(TAG_ADDRESS_INIT, jdAddressBean);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            initAddress = (JDAddressBean) getIntent().getParcelableExtra(TAG_ADDRESS_INIT);
        } else {
            initAddress = (JDAddressBean) savedInstanceState.getParcelable(TAG_ADDRESS_INIT);
        }
        presenter = new JDAddressAddEditConstract.JDAddressAddEditPresenter();
        binding = DataBindingUtil.setContentView(this, R.layout.activity_jd_address_add_edit);
        initToolbar();
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(TAG_ADDRESS_INIT, initAddress);
    }

    private void initToolbar() {
        ToolbarManager.setToolbar(this, binding.toolbar);
        if (initAddress != null) {
            binding.toolbar.setTitle("编辑地址");
        } else {
            binding.toolbar.setTitle("添加地址");
        }
    }

    private void initViews(Bundle savedInstanceState) {

    }

    private void initEvents(Bundle savedInstanceState) {
        receiveNameObservable = RxTextView.afterTextChangeEvents(binding.receiveName)
                .compose(bindToLifecycleDestroy())
                .map(new Function<TextViewAfterTextChangeEvent, String>() {
                    @Override
                    public String apply(TextViewAfterTextChangeEvent textViewAfterTextChangeEvent) throws Exception {
                        String s = textViewAfterTextChangeEvent.editable().toString();
                        if (s == null) {
                            return "";
                        }
                        return s;
                    }
                });
        receiveAddressDetailObservable = RxTextView.afterTextChangeEvents(binding.receiveAddressDetails)
                .compose(bindToLifecycleDestroy())
                .map(new Function<TextViewAfterTextChangeEvent, String>() {
                    @Override
                    public String apply(TextViewAfterTextChangeEvent textViewAfterTextChangeEvent) throws Exception {
                        String s = textViewAfterTextChangeEvent.editable().toString();
                        if (s == null) {
                            return "";
                        }
                        return s;
                    }
                });
        receivePhoneObservable = receivePhone
                .compose(bindToLifecycleDestroy())
                .map(new Function<String, String>() {
                    @Override
                    public String apply(String s) throws Exception {
                        return s == null ? "" : s;
                    }
                });
        receiveAddressObservable = receiveAddress
                .compose(bindToLifecycleDestroy())
                .map(new Function<String, String>() {
                    @Override
                    public String apply(String s) throws Exception {
                        return s == null ? "" : s;
                    }
                });
        RxView.clicks(binding.receiveAddress)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        AddressSelectActivity.startActivity(JDAddressAddEditActivity.this, 1000, AddressSelectLevel.ADDRESS_LEVEL_4_TOWN);
                    }
                });
        RxView.clicks(binding.save)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        RequestAddModifyAddress requestAddModifyAddress = checkBeforeSave();
                        if (requestAddModifyAddress != null) {
                            presenter.saveAddress(requestAddModifyAddress);
                        }
                    }
                });
    }

    private void initData(Bundle savedInstanceState) {
        presenter.bind(this);
        setResult(Activity.RESULT_CANCELED);
    }

    @Override
    public void onUser(User user) {
        this.userInfo = user;
        if (initAddress != null) {
            binding.receiveName.setText(initAddress.getReviceName());

            binding.receivePhone.setText(initAddress.getRevicePhone());
            receivePhone.onNext(initAddress.getRevicePhone());

            String address = initAddress.getProvinceStr() + initAddress.getCityStr() + initAddress.getCountryStr() + initAddress.getTownStr();
            selectedProvince = new AddressBean();
            selectedProvince.setId(Integer.parseInt(initAddress.getProvince()));
            selectedProvince.setName(initAddress.getProvinceStr());
            selectedCity = new AddressBean();
            selectedCity.setId(Integer.parseInt(initAddress.getCity()));
            selectedCity.setName(initAddress.getCityStr());
            selectedCountry = new AddressBean();
            selectedCountry.setId(Integer.parseInt(initAddress.getCountry()));
            selectedCountry.setName(initAddress.getCountryStr());
            if (!TextUtils.isEmpty(initAddress.getTown())) {
                selectedTown = new AddressBean();
                selectedTown.setId(Integer.parseInt(initAddress.getTown()));
                selectedTown.setName(initAddress.getTownStr());
            }
            binding.receiveAddress.setText(address);
            receiveAddress.onNext(address);
            binding.receiveAddressDetails.setText(initAddress.getAddress());
        } else {
            binding.receivePhone.setText(user.getPhone());
            receivePhone.onNext(user.getPhone());
        }
    }

    private RequestAddModifyAddress checkBeforeSave() {
        String receiveName = binding.receiveName.getText().toString();
        String receivePhone = binding.receivePhone.getText().toString();
        String receiveAddress = binding.receiveAddress.getText().toString();
        String receiveAddressDetails = binding.receiveAddressDetails.getText().toString();
        if (TextUtils.isEmpty(receiveName)) {
            ToastManager.show(this, "请输入收货人姓名");
            return null;
        }
        if (TextUtils.isEmpty(receivePhone)) {
            ToastManager.show(this, "请输入联系电话");
            return null;
        }
        if (TextUtils.isEmpty(receiveAddress)) {
            ToastManager.show(this, "请选择地区");
            return null;
        }
        if (TextUtils.isEmpty(receiveAddressDetails)) {
            ToastManager.show(this, "请输入详细地址");
            return null;
        }
        RequestAddModifyAddress requestAddModifyAddress = new RequestAddModifyAddress();
        requestAddModifyAddress.setReviceName(receiveName);
        requestAddModifyAddress.setPhone(userInfo.getPhone());
        requestAddModifyAddress.setRevicePhone(receivePhone);
        requestAddModifyAddress.setAddress(receiveAddressDetails);
        requestAddModifyAddress.setProvince(String.valueOf(selectedProvince.getId()));
        requestAddModifyAddress.setProvinceStr(selectedProvince.getName());
        requestAddModifyAddress.setCity(String.valueOf(selectedCity.getId()));
        requestAddModifyAddress.setCityStr(selectedCity.getName());
        requestAddModifyAddress.setCountry(String.valueOf(selectedCountry.getId()));
        requestAddModifyAddress.setCountryStr(selectedCountry.getName());
        if (selectedTown != null) {
            requestAddModifyAddress.setTown(String.valueOf(selectedTown.getId()));
            requestAddModifyAddress.setTownStr(selectedTown.getName());
        } else {
            requestAddModifyAddress.setTown("0");
            requestAddModifyAddress.setTownStr("");
        }
        requestAddModifyAddress.setEmail(userInfo.getEmail());
        if (initAddress != null) {
            requestAddModifyAddress.setId(initAddress.getId());
        }
//        requestAddModifyAddress.setSource();
        return requestAddModifyAddress;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
            ArrayList<AddressBean> selectedAddresses =  data.getParcelableArrayListExtra("data");
            selectedProvince = selectedAddresses.get(0);
            selectedCity = selectedAddresses.get(1);
            selectedCountry = selectedAddresses.get(2);
            String address;
            if (selectedAddresses.size() == 4) {
                selectedTown = selectedAddresses.get(3);
                address = selectedProvince.getName() + selectedCity.getName() + selectedCountry.getName() + selectedTown.getName();
            } else {
                selectedTown = null;
                address = selectedProvince.getName() + selectedCity.getName() + selectedCountry.getName();
            }
            binding.receiveAddress.setText(address);
        }
    }

    @Override
    public void saveAddressSuccess() {
        setResult(Activity.RESULT_OK);
        finish();
    }

    @Override
    public void saveAddressServerFailed(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public void saveAddressNetFailed(String message) {
        ToastManager.show(this, message);
    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(this, dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }

}
